package controllers;

import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import org.apache.commons.io.FileUtils;

import models.cms.Resource;
import models.cms.Resource.ResourceType;
import play.data.Upload;
import play.db.jpa.JPABase;
import play.mvc.Controller;
import play.mvc.With;
import ret.Ret;
import swagger.annotations.ApiInfo;
import utils.ResourceUtils;
import utils.SessionUtils;

@With(LoginFilter.class)
@ApiInfo(desc = "资源模块")
public class R extends SController {

    public static void index() {
        List<Resource> resources = Resource.find("order by created_at desc")
                .fetch(20);
        render(resources);
    }

    public static void view_resource(long id) {
        Resource resource = Resource.findById(id);
        render(resource);
    }

    @ApiInfo(desc = "查看文件")
    public static void raw(String hash, String type) throws IOException {
        Resource resource = Resource.find("hash = ?", hash).first();
        response.setContentTypeIfNotSet(resource.content_type);
        response.setHeader("Last-Modified", "1970-01-01");
        renderBinary(ResourceUtils.open(resource,type));
    }

    @ApiInfo(desc = "上传文件")
    public static void file_upload(Upload file) throws IOException {
        Resource res = ResourceUtils.process(file);
        renderJSON(Ret.ok().data("url", "/rest/r/raw?hash="+res.hash).datas());
    }

}
